﻿using System;
using System.Drawing;
using SFML.Graphics;

namespace SFMLPlatformerEngine {

	class GameObject {

		public char id;
		public Sprite sprite;
		public ObjectType type;
		public Point position;
		public Size size;
		public bool animated;
		public int frames;
		public float speed;

		public GameObject() { }

		public GameObject(char id, ObjectType type, Point position, Size size, bool animated, float speed, int frames) {
			this.id = id;
			this.type = type;
			this.position = position;
			this.size = size;
			this.animated = animated;
			this.frames = frames;
			this.speed = speed;

			sprite = SetSpriteImage(this);
		}

		public static GameObject FromString(string gObject) {
			string[] s = gObject.Trim().Split('|');
			GameObject go = new GameObject {
				id = Convert.ToChar(s[0].Trim()),
				type = ConvType(s[1].Trim()),
				position = ConvPos(s[2].Trim()),
				size = new Size(32, 32),
				animated = !String.IsNullOrEmpty(s[3].Trim()),
				speed = !String.IsNullOrEmpty(s[3].Trim()) ? Convert.ToSingle(s[3].Trim()) : 1,
				frames = !String.IsNullOrEmpty(s[4].Trim()) ? Convert.ToInt32(s[4].Trim()) : 0
			};
			go.sprite = SetSpriteImage(go);
			return go;
		}

		static ObjectType ConvType(string s) {
			switch(s) {
				case "dec":
					return ObjectType.Decor;
				case "res":
					return ObjectType.Resource;
				default:
					return ObjectType.Unkown;
			}
		}

		static Point ConvPos(string s) {
			string[] v = s.Split(',');
			return new Point(Convert.ToInt32(v[0]), Convert.ToInt32(v[1]));
		}

		static Sprite SetSpriteImage(GameObject go) {
			Sprite s = new Sprite();
			if(go.type == ObjectType.Decor)
				s.Texture = new Texture("res/map.png");
			if(go.type == ObjectType.Resource)
				s.Texture = new Texture("res/items.png");
			s.TextureRect = new IntRect(go.position.X * go.size.Width, go.position.Y * go.size.Height, go.size.Width, go.size.Height);
			return s;
		}

		float cFrame;

		public void Update(float time) {
			if(!animated)
				return;

			cFrame += 0.005f * speed * time;
			if(cFrame > frames)
				cFrame -= frames;

			sprite.TextureRect = new IntRect((position.X * size.Width) + ((int)cFrame * size.Width), position.Y * size.Height, size.Width, size.Height);
		}
	}
}
